<?php
/**
 * admin service file Created by PhpStorm.
 * User: wumengmeng
 * Date: 2019/08/29
 * Time: 16:52
 */

namespace Modules\Admin\Service;

use DB;
use HiCommon\Repository\GoodsRepository;
use HiCommon\Repository\GoodsCateRepository;
use HiCommon\Repository\GoodsImgRepository;
use HiCommon\Repository\GoodsSpecsCateRepository;
use HiCommon\Repository\GoodsSpecsRepository;
use HiCommon\Repository\GoodsProductRepository;
use HiCommon\Repository\MaintainConfigRepository;
use HiCommon\Repository\MaintainShopRepository;

class GoodsService
{
    /**
     * 获取分页数据
     *
     * @return array
     * @author wumengmeng <wu_mengmeng@foxmail.com>
     */
    public function get_list($arr_option)
    {
        try {
            $data = GoodsRepository::get_all($arr_option);

            $data->appends($arr_option);//添加链接参数
            $data = list_page_data($data, $arr_option);
            $data['cate'] = GoodsCateRepository::get_cate_list(['pid' => 0]);

            return hello_success('成功', $data);
        } catch (\Exception $exception) {
            return hello_error('失败', [], $exception->getMessage());
        }
    }

    /**
     * 获取商品分类列表
     */
    public function get_cate_list()
    {
        $res = GoodsCateRepository::get_cate_list(['pid' => 0, 'status' => 1]);
        $ordinary = array();
        $integral = array();
        foreach ($res as $key => $value) {
            if ($value['type'] == 1) {
                $ordinary[] = $value;
            } else {
                $integral[] = $value;
            }
        }

        return ['ordinary' => $ordinary, 'integral' => $integral];
    }

    /**
     * 获取商品规格属性列表
     */
    public function get_specs_cate_list($shop_id)
    {
        $where = ['repairstore_id' => $shop_id, 'status' => 1];
        return GoodsSpecsCateRepository::get_specs_cate_list($where);
    }

    /**
     * 获取保养配置
     */
    public function get_maintain_config($pid = 0)
    {
        try {
            $arr_Shop['field'] = ['id', 'maintain_config_id'];
            $arr_option = ['field' => ['id', 'pid', 'name'], 'where' => ['pid' => $pid]];
            $data = MaintainConfigRepository::get_all($arr_option)->toarray();

            return hello_success('成功', $data);
        } catch (\Exception $exception) {
            return hello_error('失败', [], $exception->getMessage());
        }
    }

    /**
     * 添加一条数据
     *
     * @param $arr_input
     *
     * @return array|\Illuminate\Http\RedirectResponse
     * @author wumengmeng <wu_mengmeng@foxmail.com>
     */
    public function add_one($arr_input)
    {
        $arr_input = hi_array_del_null($arr_input);
        try {
            //计算最小价格
            $arr_input['goods']['min_price'] = min(array_column($arr_input['product'], 'price'));

            $res = GoodsRepository::add_one($arr_input['goods'])->toarray();
            if (!empty($res)) {
                $goods_id = $res['id'];
                if ($arr_input['product']) {
                    self::add_goods_product($goods_id, $arr_input);
                }

                if ($arr_input['img']) {
                    self::add_goods_img($goods_id, $arr_input['img']);
                }

                return hello_success('成功', $res);
            }

            return hello_error('添加失败');
        } catch (\Exception $exception) {
            return hello_error('失败', [], $exception->getMessage());
        }
    }

    /**
     * 插入商品规格属性
     */
    public function add_goods_product($goods_id, $data)
    {
        foreach ($data['product'] as $key => $value) {
            $specs['goods_specs_cate_id'] = $data['specs_cate_id'];
            $specs['name'] = $value['name'];
            $detail = GoodsSpecsRepository::add_one($specs);

            if ($detail) {
                $product['goods_id'] = $goods_id;
                $product['goods_specs_id'] = $detail->id;
                $product['price'] = $value['price'];
                $product['integral'] = $value['integral'];
                $product['stock'] = $value['stock'];
                $product['pic'] = $value['pic'];
                GoodsProductRepository::add_one($product);
            }
        }

    }

    /**
     * 插入商品图片
     */
    public function add_goods_img($goods_id, $imgArray)
    {
        //批量插入商品图片
        $data = array();
        $time = date('Y-m-d', time());
        foreach ($imgArray as $key => $value) {
            $data[$key]['goods_id'] = $goods_id;
            $data[$key]['picurl'] = $value;
            $data[$key]['sort'] = $key + 1;
            $data[$key]['created_at'] = $time;
            $data[$key]['updated_at'] = $time;
        }

        return GoodsImgRepository::add_more($data);
    }

    /**
     * 查询一条数据
     *
     * @param int $n_id
     *
     * @return mixed
     * @author wumengmeng <wu_mengmeng@foxmail.com>
     */
    public function get_one(int $n_id)
    {
        try {
            $n_id = (int)$n_id;
            if ($n_id <= 0) {
                hello_error('数据ID不能为空');
            }

            //查询
            $arr_option['with'] = ['product', 'img'];
            $res = GoodsRepository::get_one($n_id, (array)$arr_option)->toarray();
            $res['specs_cate_id'] = $res['product'][0]['specs']['goods_specs_cate_id'];

            if (empty($res)) {
                return hello_error('查询失败');
            }

            return hello_success('查询成功', $res);
        } catch (\Exception $exception) {
            return hello_error('失败', [], $exception->getMessage());
        }
    }

    /**
     * 修改一条数据
     *
     * @param array $arr_input
     *
     * @return array|\Illuminate\Http\RedirectResponse
     * @author wumengmeng <wu_mengmeng@foxmail.com>
     */
    public function edit_one(array $arr_input)
    {
        $arr_input = hi_array_del_null($arr_input);
        try {

            $arr_input['goods']['id'] = (int)$arr_input['goods']['id'];
            if ($arr_input['goods']['id'] <= 0) {
                return hello_error('数据id不能为空');
            }

            //计算最小价格
            $arr_input['goods']['min_price'] = min(array_column($arr_input['product'], 'price'));

            $res = GoodsRepository::edit_one($arr_input['goods']);

            if ($res === false) {
                return hello_error('操作失败');
            }

            self::edit_goods_product($arr_input);

            self::edit_goods_img($arr_input['goods']['id'], $arr_input['img']);

            return hello_success('成功');
        } catch (\Exception $exception) {
            return hello_error('失败', [], $exception->getMessage());
        }
    }

    /**
     * 编辑规格属性
     */
    public function edit_goods_product($data = [])
    {
        foreach ($data['product'] as $key => $value) {
            $specs_id = $value['name_id'] ?? 0;
            $specs['goods_specs_cate_id'] = $data['specs_cate_id'];
            $specs['name'] = $value['name'];
            $res = GoodsSpecsRepository::edit_or_create(['id' => $specs_id], $specs);

            $product_id = $value['id'] ?? 0;
            $product['goods_id'] = $data['goods']['id'];
            $product['goods_specs_id'] = $res->id;
            $product['price'] = $value['price'];
            $product['integral'] = $value['integral'];
            $product['stock'] = $value['stock'];
            $product['pic'] = $value['pic'];
            GoodsProductRepository::edit_or_create(['id' => $product_id], $product);
        }

    }

    /**
     * 编辑商品图片
     */
    public function edit_goods_img($goods_id, $imgArray)
    {
        if ($imgArray) {
            $img = array();
            foreach ($imgArray as $key => $value) {
                $img['goods_id'] = $goods_id;
                $img['picurl'] = $value['url'];
                $img['sort'] = $key + 1;
                GoodsImgRepository::edit_or_create(['id' => $value['id']], $img);
            }
        }

    }

    /**
     * 修改单个字段
     *
     * @param $arr_input
     *
     * @return array
     * @author wumengmeng <wu_mengmeng@foxmail.com>
     */
    public function change_one_state($arr_input)
    {
        try {
            $arr_input['id'] = (int)$arr_input['id'];
            if ($arr_input['id'] <= 0) {
                return hello_error('数据id不能为空');
            }

            $res = GoodsRepository::edit_one($arr_input);
            if ($res === false) {
                return hello_error('操作失败');
            }
            return hello_success('成功');
        } catch (\Exception $exception) {
            return hello_error('失败', [], $exception->getMessage());
        }
    }

    /**
     * 删除一条数据
     *
     * @param int $n_id
     *
     * @return array|\Illuminate\Http\RedirectResponse
     * @author wumengmeng <wu_mengmeng@foxmail.com>
     */
    public function delete_one($n_id)
    {
        try {
            if ($n_id <= 0) {
                return hello_error('数据id不能为空');
            }

            $res = GoodsRepository::delete_one($n_id);
            if ($res === false) {
                return hello_error('操作失败');
            }
            return hello_success('成功');

        } catch (\Exception $exception) {
            return hello_error('失败', [], $exception->getMessage());
        }
    }

    /**
     * 删除图片
     */
    public function delPic($n_id)
    {
        try {
            if ($n_id <= 0) {
                return hello_error('数据id不能为空');
            }

            $res = GoodsImgRepository::delete_one($n_id);
            if ($res === false) {
                return hello_error('操作失败');
            }
            return hello_success('成功');

        } catch (\Exception $exception) {
            return hello_error('失败', [], $exception->getMessage());
        }
    }

    /**
     * 删除商品规格属性
     */
    public function delProduct($n_id)
    {
        try {
            if ($n_id <= 0) {
                return hello_error('数据id不能为空');
            }

            $res = GoodsProductRepository::delete_one($n_id);
            if ($res === false) {
                return hello_error('操作失败');
            }
            return hello_success('成功');

        } catch (\Exception $exception) {
            return hello_error('失败', [], $exception->getMessage());
        }
    }

}